"""
用户服务主应用程序
==================

FastAPI应用程序入口点，使用RedFire统一架构。
"""

import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

from redfire_framework import get_service_settings
from redfire_framework.core.exceptions import RedFireException

from .api.v1 import api_router
from .containers import UserServiceContainer
from .config import UserServiceSettings
# 导入需要wiring的模块
from .api.v1 import auth, users
from .services import user_service as user_service_module
from .repositories import user_repository as user_repository_module

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用程序生命周期管理"""
    logger.info("用户服务启动中...")
    
    try:
        # 【重要变更】加载用户服务专用配置
        settings = UserServiceSettings(service_name="user_service")
        
        # 创建并配置容器，传入数据库配置
        container = UserServiceContainer.create_for_service(
            service_name="user_service",
            settings=settings,
            database_configs=settings.databases  # 使用新的databases属性
        )
        
        # 验证容器资源可用性（新的方式）
        try:
            # 验证核心服务可用性
            db_manager = container.database_manager()
            security = container.security_service()
            logger.info("用户服务容器资源验证完成")
        except Exception as e:
            logger.error(f"容器资源验证失败: {e}")
            raise
        
        # 配置依赖注入wiring（使用导入的模块对象而不是字符串路径）
        container.wire(modules=[
            auth,
            users,
            user_service_module,
            user_repository_module
        ])
        
        # 将容器绑定到应用程序
        app.container = container
        app.settings = settings
        
        logger.info("用户服务启动完成")
        yield
        
    except Exception as e:
        logger.error(f"用户服务启动失败: {e}")
        raise
    finally:
        # 清理容器资源
        logger.info("用户服务关闭中...")
        if hasattr(app, 'container') and app.container:
            try:
                # 清理数据库连接
                if hasattr(app.container, 'database_manager'):
                    db_manager = app.container.database_manager()
                    if hasattr(db_manager, 'close_all'):
                        await db_manager.close_all()
                        logger.info("数据库连接已关闭")
            except Exception as e:
                logger.error(f"清理资源失败: {e}")
            try:
                app.container.unwire()
            except Exception as e:
                logger.error(f"解除wiring失败: {e}")
        logger.info("用户服务关闭完成")


def create_app() -> FastAPI:
    """创建FastAPI应用程序"""
    # 临时加载配置用于应用创建
    settings = UserServiceSettings()
    
    app = FastAPI(
        title="用户服务 API",
        description="RedFire 用户管理服务",
        version="1.0.0",
        lifespan=lifespan,
        docs_url="/docs" if settings.is_development else None,
        redoc_url="/redoc" if settings.is_development else None,
    )
    
    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"] if settings.is_development else [],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 添加响应包装中间件
    from .middleware import ResponseWrapperMiddleware
    app.add_middleware(ResponseWrapperMiddleware)
    
    # 添加路由
    app.include_router(api_router, prefix="/api/v1")
    
    # 注册异常处理器
    register_exception_handlers(app)
    
    # 添加中间件
    register_middleware(app)
    
    return app


def register_exception_handlers(app: FastAPI):
    """注册异常处理器"""
    
    @app.exception_handler(RedFireException)
    async def service_exception_handler(request: Request, exc: RedFireException):
        """处理服务异常"""
        logger.error(f"服务异常: {exc.message}")
        return JSONResponse(
            status_code=status.HTTP_400_BAD_REQUEST,
            content=exc.to_dict()
        )
    
    @app.exception_handler(StarletteHTTPException)
    async def http_exception_handler(request: Request, exc: StarletteHTTPException):
        """处理HTTP异常"""
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "error_code": "HTTP_ERROR",
                "message": exc.detail,
                "details": {}
            }
        )
    
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        """处理请求验证异常"""
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content={
                "error_code": "VALIDATION_ERROR",
                "message": "请求数据验证失败",
                "details": {
                    "field_errors": [
                        {
                            "field": ".".join(str(loc) for loc in error["loc"]),
                            "message": error["msg"],
                            "type": error["type"]
                        }
                        for error in exc.errors()
                    ]
                }
            }
        )
    
    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        """处理通用异常"""
        logger.error(f"未处理的异常: {str(exc)}", exc_info=exc)
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={
                "error_code": "INTERNAL_SERVER_ERROR",
                "message": "服务器内部错误",
                "details": {}
            }
        )


def register_middleware(app: FastAPI):
    """注册中间件"""
    
    @app.middleware("http")
    async def logging_middleware(request: Request, call_next):
        """请求日志中间件"""
        import time
        
        start_time = time.time()
        
        # 记录请求信息
        logger.info(
            f"请求开始: {request.method} {request.url.path} "
            f"- IP: {request.client.host if request.client else 'unknown'}"
        )
        
        try:
            response = await call_next(request)
            
            # 记录响应信息
            process_time = time.time() - start_time
            logger.info(
                f"请求完成: {request.method} {request.url.path} "
                f"- 状态码: {response.status_code} "
                f"- 耗时: {process_time:.3f}s"
            )
            
            # 添加响应头
            response.headers["X-Process-Time"] = str(process_time)
            return response
                
        except Exception as e:
            process_time = time.time() - start_time
            logger.error(
                f"请求异常: {request.method} {request.url.path} "
                f"- 异常: {str(e)} "
                f"- 耗时: {process_time:.3f}s",
                exc_info=e
            )
            raise


# 创建应用程序实例
app = create_app()


@app.get("/health")
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "service": "user_service",
        "version": "1.0.0"
    }


@app.get("/")
async def root():
    """根端点"""
    return {
        "message": "用户服务 API",
        "version": "1.0.0",
        "docs_url": "/docs"
    }


if __name__ == "__main__":
    import uvicorn
    
    settings = UserServiceSettings()
    uvicorn.run(
        "app.main:app",
        host=settings.api_host,
        port=settings.api_port,
        reload=settings.is_development,
        log_level=settings.log_level.lower()
    )
